package util;
import java.sql.*;
public class DBConnection {
	private Connection conn=null;
	private String url="jdbc:mysql://localhost/elearning?useUnicode=true&characterEncoding=gb2312";
	private String user="root";
	private String password="123";
	public boolean connect(){
		try{
			Class.forName("com.mysql.jdbc.Driver");
			conn=DriverManager.getConnection(url,user,password);
		}catch(Exception e){
			System.out.println("Drivers load Error");
			e.printStackTrace();
			return false;
		}
		return true;
	}
	public PreparedStatement prepare(String sql) {
		PreparedStatement pstmt = null; 
		if(conn==null)
			connect();
		try {
			
			pstmt = conn.prepareStatement(sql);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
	}
	
	public PreparedStatement prepare(String sql, int autoGenereatedKeys) {
		PreparedStatement pstmt = null; 
		if(conn==null)
			connect();
		try {
			
			pstmt = conn.prepareStatement(sql, autoGenereatedKeys);

		} catch (SQLException e) {
			e.printStackTrace();
		}
		return pstmt;
	}
	
	public Statement getStatement() {
		Statement stmt = null; 
		if(conn==null)
			connect();
		try {
			
			stmt = conn.createStatement();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return stmt;
	}
	
	/*
	public ResultSet getResultSet(String sql) {
		Statement stmt = getStatement(conn);
		ResultSet rs = getResultSet(stmt, sql);
		close(stmt);
		return rs;
	}
	*/
	public ResultSet executeQuery(String sql){
		Statement stmt = null;
		ResultSet rs = null;
		if(conn==null)
			connect();
		try {
			
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	public ResultSet getResultSet(Statement stmt, String sql) {
		ResultSet rs = null;
		try {
			if(stmt != null) {
				rs = stmt.executeQuery(sql);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
	
	public boolean executeUpdate(String sql) {
		Statement stmt = null;
		if(conn==null)
			connect();
		try {
			stmt = conn.createStatement();
			int count=stmt.executeUpdate(sql);
			if(count<1)
				return false;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return true;
	}
	
	public void close() {
		try {
			if(conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void close(Statement stmt) {
		try {
			if(stmt != null) {
				stmt.close();
				stmt = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void close(ResultSet rs) {
		try {
			if(rs != null) {
				rs.close();
				rs = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
